<template>
  <div class="page">
    <!-- 筛选：名称 / 状态 / 层级 -->
    <el-form :inline="true" :model="query" class="mb-12">
      <el-form-item label="分类名称">
        <el-input v-model="query.name" placeholder="请输入分类名称" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.status" placeholder="全部" clearable>
          <el-option label="启用" value="enabled" />
          <el-option label="禁用" value="disabled" />
        </el-select>
      </el-form-item>
      <el-form-item label="层级">
        <el-select v-model="query.level" placeholder="全部" clearable>
          <el-option label="一级" value="1" />
          <el-option label="二级" value="2" />
          <el-option label="三级" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作：新增、批量启用/禁用 -->
    <div class="mb-12">
      <el-button type="primary" @click="openEdit()">新增分类</el-button>
      <el-button :disabled="!selection.length" @click="onBatchStatus('enabled')">批量启用</el-button>
      <el-button type="warning" :disabled="!selection.length" @click="onBatchStatus('disabled')">批量禁用</el-button>
    </div>

    <!-- 树形表格：展示全部层级关系，支持折叠/展开 -->
    <el-table
      :data="tableData"
      row-key="id"
      border
      default-expand-all
      :tree-props="{ children: 'children' }"
      @selection-change="selection = $event"
    >
      <el-table-column type="selection" width="48" />
      <el-table-column prop="name" label="分类名称" min-width="200" />
      <el-table-column prop="level" label="层级" width="80" />
      <el-table-column prop="sort" label="排序" width="160">
        <template #header>
          <span>排序优先级</span>
        </template>
        <template #default="{ row }">
          <!-- 使用下拉选择替换不统一的输入框，减少误操作 -->
          <el-select v-model="row.sort" placeholder="选择优先级" size="small" @change="onSortChange(row)">
            <el-option v-for="n in sortOptions" :key="n" :label="`优先级 ${n}`" :value="n" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status==='enabled'?'success':'info'">{{ row.status==='enabled'?'启用':'禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updatedAt" label="更新时间" min-width="180" />
      <el-table-column label="操作" width="260">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="openEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" plain @click="onDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑弹窗：父分类选择（树形选择器）、排序、状态、描述 -->
    <el-dialog v-model="visible" :title="form.id ? '编辑分类' : '新增分类'" width="640px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="父分类">
          <CategoryTreeSelect v-model="form.parentId" :show-only-enabled="false" :only-leaf="false" placeholder="不选择则为顶级分类" />
        </el-form-item>
        <el-form-item label="排序值" prop="sort">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="form.description" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visible=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="onSubmit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 分类管理页面：树形结构展示、增删改查、批量启用/禁用、排序值调整
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CategoryTreeSelect from '../components/CategoryTreeSelect.vue'
// 保留本地数据构建作为兜底，但 CRUD 改为调用后端接口
import { categories, getTree } from '../store/categories'
import { getCategoryTree, createCategory, updateCategoryApi, deleteCategoryApi, batchSetCategoryStatus, updateCategorySort } from '../api/category'

// 查询条件
const query = reactive({ name: '', status: '', level: '' })
const selection = ref([])
// 排序选项（示例为 0-9，可按需调整范围或来源）
const sortOptions = Array.from({ length: 10 }, (_, i) => i)

// 表格数据：根据筛选进行计算
// 服务端分类树数据
const serverTree = ref([])

// 将服务端状态数值转换为前端展示用的状态文本
function normalizeTree(nodes){
  return nodes.map(n => ({
    id: n.id,
    name: n.name,
    parentId: n.parentId,
    level: n.level,
    sort: n.sort,
    status: n.status === 1 ? 'enabled' : 'disabled',
    description: n.description,
    updatedAt: n.updateTime,
    children: n.children ? normalizeTree(n.children) : []
  }))
}

// 过滤并渲染的表格数据（优先使用服务端数据）
const tableData = computed(() => {
  const source = serverTree.value.length ? serverTree.value : getTree(categories.value)
  const match = (x) => {
    const nameOk = query.name ? x.name.includes(query.name) : true
    const statusOk = query.status ? x.status === query.status : true
    const levelOk = query.level ? String(x.level) === String(query.level) : true
    return nameOk && statusOk && levelOk
  }
  const clone = (nodes) => nodes.map(n => ({ ...n, children: n.children ? clone(n.children) : [] }))
  const filtered = (nodes) => nodes.map(n => {
    const ch = n.children ? filtered(n.children) : []
    const keepSelf = match(n)
    const keepChild = ch.length > 0
    if (keepSelf || keepChild) return { ...n, children: ch }
    return null
  }).filter(Boolean)
  return filtered(clone(source))
})

// 编辑弹窗
const visible = ref(false)
const saving = ref(false)
const formRef = ref()
const form = reactive({ id: null, name: '', parentId: null, sort: 1, status: 'enabled', description: '' })
const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序值', trigger: 'change' }]
}

function onSearch(){}
function onReset(){ query.name=''; query.status=''; query.level='' }

function openEdit(row){
  if(row){
    Object.assign(form, { id: row.id, name: row.name, parentId: row.parentId || null, sort: row.sort, status: row.status, description: row.description || '' })
  } else {
    Object.assign(form, { id: null, name: '', parentId: null, sort: 1, status: 'enabled', description: '' })
  }
  visible.value = true
}

function onSubmit(){
  formRef.value.validate((ok)=>{
    if(!ok) return
    // 编辑/新增保存前二次确认，避免误操作
    ElMessageBox.confirm('确认保存该分类信息吗？', '提示', { type: 'warning' }).then(()=>{
      saving.value = true
      const payload = {
        name: form.name,
        parentId: form.parentId || 0,
        sort: form.sort,
        // 后端使用数值状态：1=启用，0=禁用
        status: form.status === 'enabled' ? 1 : 0,
        description: form.description
      }
      const p = form.id ? updateCategoryApi(form.id, payload) : createCategory(payload)
      p.then(async (res) => {
        if(res.code === 200){
          ElMessage.success(res.message || '保存成功')
          visible.value = false
          // 刷新服务端分类树
          const r = await getCategoryTree()
          if(r.code === 200){ serverTree.value = normalizeTree(r.data) }
        } else {
          ElMessage.error(res.message || '保存失败')
        }
      }).catch(()=>{
        ElMessage.error('保存失败：网络或服务端错误')
      }).finally(()=>{ saving.value = false })
    })
  })
}

function onDelete(row){
  ElMessageBox.confirm('删除前将校验是否存在子分类或关联商品，确认删除？', '提示', { type: 'warning' }).then(()=>{
    deleteCategoryApi(row.id).then(async (res)=>{
      if(res.code === 200){
        ElMessage.success(res.message || '删除成功')
        const r = await getCategoryTree(); if(r.code===200){ serverTree.value = normalizeTree(r.data) }
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }).catch(()=>{
      ElMessage.error('删除失败：网络或服务端错误')
    })
  })
}

function onBatchStatus(status){
  const ids = selection.value.map(x => x.id)
  const s = status === 'enabled' ? 1 : 0
  batchSetCategoryStatus(ids, s).then(async (res)=>{
    if(res.code === 200){
      ElMessage.success(`批量${status==='enabled'?'启用':'禁用'}成功`)
      const r = await getCategoryTree(); if(r.code===200){ serverTree.value = normalizeTree(r.data) }
    } else {
      ElMessage.error(res.message || '批量操作失败')
    }
  }).catch(()=>{
    ElMessage.error('批量操作失败：网络或服务端错误')
  })
}

function onSortChange(row){
  // 排序值即时更新；真实场景应调用后端接口保存
  updateCategorySort(row.id, row.sort).then((res)=>{
    if(res.code === 200){ ElMessage.success('排序优先级已更新') }
    else { ElMessage.error(res.message || '排序更新失败') }
  }).catch(()=>{ ElMessage.error('排序更新失败：网络或服务端错误') })
}

// 挂载时调用后端分类树接口
onMounted(async () => {
  try {
    const res = await getCategoryTree()
    if(res.code === 200 && Array.isArray(res.data)){
      serverTree.value = normalizeTree(res.data)
    } else {
      ElMessage.error(res.message || '获取分类树失败')
    }
  } catch (e) {
    // 未登录或网络错误已由拦截器处理；这里不重复提示
    console.warn('getCategoryTree error:', e)
  }
})
</script>

<style scoped>
.page { background: #fff; padding: 12px 16px; border: 1px solid #ebeef5; border-radius: 8px; }
.mb-12 { margin-bottom: 12px; }

/* 表格与操作区更紧凑的现代风格 */
:deep(.el-table) { --el-table-border-color: #ebeef5; }
:deep(.el-table .el-button.is-plain) { border-radius: 6px; }
:deep(.el-form-item) { margin-right: 8px; }
</style>